package com.shardingsphere.example.service;

import com.shardingsphere.example.annotation.ShardingTable;
import com.shardingsphere.example.entity.User;
import com.shardingsphere.example.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 保存用户（自动路由到对应分表）
     */
    @ShardingTable(logicTable = "user", shardingKey = "userId")
    public boolean save(User user) {
        try {
            int result = userMapper.insert(user);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据userId查询用户（自动路由到对应分表）
     */
    @ShardingTable(logicTable = "user", shardingKey = "userId")
    public User getUserByUserId(String userId) {
        return userMapper.selectByUserId(userId);
    }

    /**
     * 根据年龄查询用户（查询所有分表并合并结果）
     */
    public List<User> getUsersByAge(Integer age) {
        List<User> allUsers = new ArrayList<>();

        // 遍历所有分表查询
        for (int i = 0; i < 2; i++) {
            try {
                // 手动设置表名上下文
                com.shardingsphere.example.sharding.ShardingContextHolder.setTableName("user_" + i);
                List<User> users = userMapper.selectByAge(age);
                if (users != null) {
                    allUsers.addAll(users);
                }
            } finally {
                com.shardingsphere.example.sharding.ShardingContextHolder.clear();
            }
        }

        return allUsers;
    }

    /**
     * 获取所有用户（查询所有分表并合并结果）
     */
    public List<User> getAllUsers() {
        List<User> allUsers = new ArrayList<>();

        // 遍历所有分表查询
        for (int i = 0; i < 2; i++) {
            try {
                // 手动设置表名上下文
                com.shardingsphere.example.sharding.ShardingContextHolder.setTableName("user_" + i);
                List<User> users = userMapper.selectAll();
                if (users != null) {
                    allUsers.addAll(users);
                }
            } finally {
                com.shardingsphere.example.sharding.ShardingContextHolder.clear();
            }
        }

        return allUsers;
    }
}
